package com.nut.spp.jbb.impl;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.nut.spp.api.req.PrepayReq;
import com.nut.spp.api.resp.PrepayResp;
import com.nut.spp.common.PayInfo;
import com.nut.spp.common.RefundInfo;
import com.nut.spp.enums.IdTagEnum;
import com.nut.spp.jbb.JbbService;
import com.nut.spp.jbb.req.CorpReq;
import com.nut.spp.jbb.req.SettleReq;
import com.nut.spp.util.IdUtil;
import com.nut.spp.util.JacksonUtils;
import com.nut.spp.util.MathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class JbbServiceImpl implements JbbService {

    @Override
    public String userUpper(String mobile) {

        String url = USER_UPPER + mobile;

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();

        //{"code":2,"data":null,"errorCode":"","msg":"用户不存在","sum":""}
        log.info(response);

        log.info("jbb_resp=" + response);

        JsonNode obj = JacksonUtils.toObj(response);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {
                return obj.get("data").get("phone").textValue();
            }
        }
        return null;

    }

    @Override
    public Boolean userCheck(String mobile) {
        String url = USER_CHECK + mobile;

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();

        //{"code":2,"data":null,"errorCode":"","msg":"用户不存在","sum":""}
        log.info("jbb_resp=" + response);

        JsonNode obj = JacksonUtils.toObj(response);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {
                return obj.get("data").asBoolean();
            }
        }
        return false;
    }

    @Override
    public void sendSms(String mobile) {

        String url = SEND_SMS + mobile;

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();

        //{"code":200,"data":null,"errorCode":"","msg":"SUCCESS","sum":""}
        log.info("jbb_resp=" + response);

    }

    @Override
    public Boolean smsCheck(String mobile, String smsCode) {

        String url = SMS_CHECK + mobile + "/" + smsCode;

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();

        //{"code":2,"data":null,"errorCode":"","msg":"用户不存在","sum":""}
        log.info("jbb_resp=" + response);

        JsonNode obj = JacksonUtils.toObj(response);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {
                return obj.get("data").asBoolean();
            }
        }
        return false;
    }

    @Override
    public String corpCreate(CorpReq req) {

        String json = JacksonUtils.toJson(req);
        log.info("jbb_url=" + CORP_CREATE);
        log.info("jbb_params=" + json);
        String body = HttpRequest.post(CORP_CREATE).body(json, "application/json").execute().body();
        log.info("jbb_resp=" + body);

        return "OK";
    }

    @Override
    public void queryPayWay() {

    }

    @Override
    public PrepayResp payPrepay(PrepayReq req) {

        String json = JacksonUtils.toJson(req);
        log.info("jbb_json=" + json);

        StringBuilder sb = new StringBuilder();
        sb.append(PAYMENT_PREPAY).append(req.getPayMethod()).append("/");

        //wx_pub,alipay_qr
        if (req.getPayWay() == 1) {
            sb.append("alipay_qr");
        } else {
            sb.append("wx_pub");
        }
        sb.append("?bizNo=").append(req.getBizNo());
        sb.append("&description=").append(req.getBody());
        sb.append("&orderNo=").append(req.getOrderNo());
        sb.append("&payAmt=").append(MathUtil.toYuan2f(req.getPayMoney()));

        if (req.getOpenId() != null) {
            sb.append("&openid=").append(req.getOpenId());
        }

        String url = sb.toString();

        log.info("jbb_url=" + url);

        String body = HttpRequest.get(url).execute().body();

        log.info("jbb_resp=" + body);

//        {
//            "code": 200,
//                "data": {
//                    "bizNo": "1234",
//                    "createdTime": "1729217341",
//                    "errorCode": "",
//                    "errorMsg": "",
//                    "expend": "{\"qrcode_url\":\"https://qr.alipay.com/bax05477clsyojpzlxku2592\"}",
//                    "object": "payment",
//                    "orderNo": "241018100840813",
//                    "payAmt": "0.02",
//                    "payApplyStatus": "succeeded",
//                    "payChannel": "alipay_qr",
//                    "payNo": "UN202410181296777048098082816",
//                    "queryUrl": "https://api.adapay.tech/v1/expire/payments/1/87f5b8392b18db490ea82bd29ca022dc",
//                    "transactionId": "002212024101810090110693171926255255552"
//        },
//            "errorCode": "",
//                "msg": "SUCCESS",
//                "sum": "0"
//        }

        JsonNode obj = JacksonUtils.toObj(body);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {

                JsonNode data = obj.get("data");

                JsonNode expend = JacksonUtils.toObj(data.get("expend").asText());
                String qrcodeUrl = expend.get("qrcode_url").asText();

                String queryUrl = data.get("queryUrl").asText();
                String payNo = data.get("payNo").asText();

                log.info("pay_qrcode_url=" + qrcodeUrl);
                log.info("pay_query_url=" + queryUrl);
                log.info("payNo=" + payNo);

                PrepayResp resp = new PrepayResp();
                resp.setPayNo(payNo);
                resp.setQueryUrl(queryUrl);
                resp.setQrcodeUrl(qrcodeUrl);
                resp.setOrderNo(req.getOrderNo());

                return resp;
            }
        }

        return null;

    }

    @Override
    public PayInfo queryPayResult(String payNo) {

        String url = PAYMENT_QUERY_RESULT + payNo;

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();

//        {
//            "code": 200,
//                "data": {
//            "msg": "查询成功",
//                    "payNo": "UN202410221298231322732662784",
//                    "payChannel": "alipay_qr",
//                    "payAmt": "0.01",
//                    "payStatus": "succeeded",
//                    "transactionId": "id"
//        },
//            "errorCode": "",
//                "msg": "SUCCESS",
//                "sum": ""
//        }

//        {
//            "code": 200,
//                "data": {
//            "msg": "查询失败",
//                    "payNo": "UN202410221298229378223968256",
//                    "payChannel": "alipay_qr",
//                    "payAmt": 20.00,
//                    "payStatus": "failed",
//                    "transactionId": "id"
//        },
//            "errorCode": "",
//                "msg": "SUCCESS",
//                "sum": ""
//        }

//        {"code":200,"data":{"msg":"查询成功","payNo":"UN202410221298231322732662784","payChannel":"alipay_qr","payAmt":"0.01","payStatus":"succeeded","transactionId":"id"},"errorCode":"","msg":"SUCCESS","sum":""}
//        {"code":200,"data":{"msg":"查询失败","payNo":"UN202410181296777048098082816","payChannel":"alipay_qr","payAmt":0.02,"payStatus":"failed","transactionId":"id"},"errorCode":"","msg":"SUCCESS","sum":""}

        log.info("jbb_resp=" + response);

        JsonNode obj = JacksonUtils.toObj(response);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {

                JsonNode data = obj.get("data");
                String payChannel = data.get("payChannel").asText();
                String payAmt = data.get("payAmt").asText();
                String payStatus = data.get("payStatus").asText();

                PayInfo payInfo = new PayInfo();
                payInfo.setPayChannel(payChannel);
                payInfo.setPayAmt(payAmt);
                payInfo.setPayStatus(payStatus);

                return payInfo;


            }
        }

        return null;

    }

    @Override
    public RefundInfo refund(String payNo, Integer money) {

        StringBuilder sb = new StringBuilder();
        sb.append(REFUND_URL).append(payNo);
        sb.append("?refundAmt=").append(MathUtil.toYuan2f(money));

        //TODO 订单类型动态
        sb.append("&requestNo=").append(IdUtil.generatedCommonId(IdTagEnum.FansRefund));

        String url = sb.toString();

        log.info("jbb_url=" + url);
        String response = HttpRequest.get(url).execute().body();
        log.info("jbb_resp=" + response);

        //{"code":200,"data":{"createdTime":"1729417111000","msg":"","refundAmt":"0.01","refundId":"0022120241020173831980694009821109587968","requestNo":"241020110002","status":"PENDING"},"errorCode":"","msg":"SUCCESS","sum":""}
        //{"code":200,"data":{"createdTime":"","msg":"退款金额超过订单金额","refundAmt":"0.01","refundId":"","requestNo":"941022110003","status":"FAILED"},"errorCode":"","msg":"SUCCESS","sum":""}

        JsonNode obj = JacksonUtils.toObj(response);
        int code = obj.get("code").asInt();
        if (code == 200) {
            if (obj.get("data") != null) {

                JsonNode data = obj.get("data");
                String refundId = data.get("refundId").asText();
                String refundAmt = data.get("refundAmt").asText();
                String status = data.get("status").asText();
                String msg = data.get("msg").asText();

                RefundInfo info = new RefundInfo();
                info.setPayNo(payNo);
                info.setRefundId(refundId);
                info.setRefundAmt(refundAmt);
                info.setStatus(status);
                info.setMsg(msg);
                info.setJson(response);

                return info;

            }
        }

        return null;

    }

    @Override
    public void settle(SettleReq req) {

        String json = JacksonUtils.toJson(req);
        log.info("jbb_settle_url=" + SETTLE);
        log.info("jbb_settle_params=" + json);
        String body = HttpRequest.post(SETTLE).body(json, "application/json").execute().body();
        log.info("jbb_settle_resp=" + body);

    }

    public static void main(String[] args) {

        String dd = "{\"qrcode_url\":\"https://qr.alipay.com/bax08288ecnbnhfrtxeg254d\"}";

        JsonNode json = JacksonUtils.toObj(dd);
        String ff = json.get("qrcode_url").asText();
        System.out.println(ff);

    }


}